<script setup>
import { onMounted, ref } from "vue"
import { getCategoryList, deleteCategory } from '@/api/category'
import { Delete, Edit } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import GoodView from './good.vue'
const tableData = ref([])
// 引入树组件
const treeProps = {
  children: 'children',
  label: 'name',
}
const goodCategroy = async () => {
  let result = await getCategoryList()
  tableData.value = result.data
}

const goodView = ref("goodView")
const addGood = () => {
  goodView.value.getData()
  goodView.value.dialogVisible = true
  goodView.value.fromData = {}
  goodView.value.title = '新增商品：'
}
//编辑
const handleEdit = (row) => {
  goodView.value.dialogVisible = true
  goodView.value.title = '修改商品：'
  goodView.value.fromData.name = JSON.parse(JSON.stringify(row.name))
  //顶级分类不显示商品类别
  if (row.parentId != 0) {
    goodView.value.fromData.id = JSON.parse(JSON.stringify(row.parentId))
  }
  // console.log('编辑', row)
}
//删除
const handleDelete = async (row) => {
  if (row.children.length > 0) {
    ElMessage.error("请先删除子类别！")
    return
  }
  let result = await deleteCategory(row.id)
  if (result.code == 200) {
    ElMessage.success("删除成功！")
    goodCategroy()
  } else {
    ElMessage.error("删除失败！")
  }
  // console.log('删除', row)
}
onMounted(() => {
  goodCategroy()
})
</script>
<template>
  <h2>商品类别管理</h2>
  <el-button type="primary" plain @click="addGood"> + 新增商品</el-button>
  <el-table :data="tableData" :tree-props="treeProps" row-key="id" :default-expand-all="false">
    <!-- <el-table-column type="selection" width="55" :selectable="selectable" align="center" /> -->
    <el-table-column prop="name" label="商品类别" align="center" />
    <el-table-column prop="createBy" label="创建人" align="center" />
    <el-table-column prop="createTime" label="创建时间" align="center" />
    <el-table-column fixed="right" label="操作" min-width="120" align="center">
      <template #default="scope">
        <el-button type="primary" :icon="Edit" circle @click="handleEdit(scope.row)" />
        <el-button type="danger" :icon="Delete" circle @click="handleDelete(scope.row)" />
      </template>
    </el-table-column>
  </el-table>
  <GoodView ref="goodView" @search="goodCategroy" />
</template>
<style scoped></style>